package com.spc.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.spc.constant.MessageConstant;
import com.spc.entity.Result;
import com.spc.service.MemberService;
import com.spc.service.ReportService;
import com.spc.service.SetMealService;
import com.spc.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetMealService setMealService;
    @Reference
    private ReportService reportService;

    //会员数量折线图数据
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> months = new ArrayList<String>();
        //计算过去12个月是什么月份
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, -1);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date time = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(time));
        }
        map.put("months", months);
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //套餐饼状图
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            List<Map<String, Object>> setmealCount = setMealService.findSetmealCount();
            data.put("setmealCount", setmealCount);
            List<String> setmealNames = new ArrayList<String>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //运营数据统计
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出Excel表格
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获得Excel模板文件绝对路径
            String realPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(realPath));
            //读取第一个模板
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }
            //使用输出流进行表格下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出PDF表格
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到PDF文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //动态获取模板文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,result,new JRBeanCollectionDataSource(hotSetmeal));
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /*
    获取会员预约数变化的数据统计,用于展示会员预约变换折线图
    无请求参数
    需要响应参数为:
    months命名的string类型的数组,存储日期
    memberCount命名的integer类型的数组,存储对应日期月份最后一天截止的会员数量
    * */
    @RequestMapping("/getMemberOrderReport")
    public Result getMemberOrderReport() {
        // 1.通过Calendar的静态方法getInstance创建calender对象(为当前日期)
        Calendar calendar = Calendar.getInstance();
        // 2.通过calender的add方法,得到24个月前的日期
        // 参数一为变换日期的月份,第二个参数为变化多少,负数表示往前推
        calendar.add(Calendar.MONTH, -24);
        // 3.此时的calender为24个月前日期,创建一个string类型的list集合,用于存储这24个月
        ArrayList<String> months = new ArrayList<>();
        // 4.进行24此for循环,每次将calender往后加1个月,并存储到list集合
        for (int i = 0; i < 24; i++) {
            // 4.1 每一次循环,将calender往后加一个月
            calendar.add(Calendar.MONTH, 1);
            // 4.2 通过calender的gettime方法,得到该日期的data对象
            Date date = calendar.getTime();
            // 4.3 需要用sinpledataformat的format方法,将date转换为yyyy.MM格式的string日期
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            String month = simpleDateFormat.format(date);
            // 4.4 将该string类型的日期添加到months集合中
            months.add(month);
        }
        try {
            // 5. 调用memberService中的getMemberOrderByMonths方法,参数为months集合,
            // 得到integer类型的list集合
            Map<String,Object> map = memberService.getMemberOrderByMonths(months);
            // 6.将该months集合放入map中,键名为months(与html页面总的折线图横坐标名相同)
            map.put("months", months);
            //7.返回result的flag为true,data为map集合
            return new Result(true, "获取会员预约统计数据成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            // 8. 如果调用远程服务失败,则返回result为false,并给出错误提示信息
            return new Result(false,"获取会员预约统计数据失败");
        }

    }


    /*
    获取本月会员预约数变化的数据统计,用于展示柱状图
     无请求参数
     需要响应参数为:
     days命名的string类型的数组,存储该月每天
     memberOrderCount命名的integer类型的数组,存储对应日期月份最后一天截止的会员数量
    * */
    @RequestMapping("/getMemberOrderReportMonth")
    public Result getMemberOrderReportMonth() {

        // 1.通过Calendar的静态方法getInstance创建calender对象(为当前日期)
        Calendar calendar = Calendar.getInstance();
        // 2.通过get方法,得到当前日的数值
        int today = calendar.get(Calendar.DATE);
        // 2.1 在将calender设置为本月的一号
        calendar.set(Calendar.DAY_OF_MONTH,1);
        //3.创建一个string类型数组,用于存储日期,用于查询数据库
        ArrayList<String> days = new ArrayList<>();
        // 4.进行for循环,次数为today的数值,
        for (int i = 1; i <=today ; i++) {
            // 4.1 通过calender的gettime方法,得到该日期的data对象
            Date date = calendar.getTime();
            // 4.2 需要用sinpledataformat的format方法,将date转换为yyyy-MM-dd格式的string日期
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String day = simpleDateFormat.format(date);
            // 4.3 将该string类型的日期添加到days集合中
            days.add(day);
            // 4.4 通过add,每次将日往后推一天
            calendar.add(Calendar.DATE, 1);
        }



        try {
            // 7. 调用memberService中的getMemberOrderByMonths方法,参数为days集合,
            // 得到integer类型的list集合
            Map<String ,Object > map = memberService.getMemberOrderByDays(days);
            //8.将该memberOrderCount集合加入map中,键名为memberOrderCount(与html页面总的折线图纵坐标名相同)
            // 6.将该days集合放入map中,键名为days(与html页面总的折线图横坐标名相同)
            map.put("days", days);
            //9.返回result的flag为true,data为map集合
            return new Result(true,"获取会员预约统计数据成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            // 10. 如果调用远程服务失败,则返回result为false,并给出错误提示信息
            return new Result(false,"获取会员预约统计数据失败");
        }

    }

}
